package com.ziJing.multithreading.sync.interview01;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program Multithreading
 * @description:
 * 曾经的面试题：（淘宝？）
 * 实现一个容器，提供两个方法，add，size
 * 写两个线程，线程1添加十个元素到容器中，
 * 线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 *
 *
 *
 *
 *
 * @author: zhangbo
 * @create: 2022/05/03 22:04
 */
public class T04_NotifyFreeLock {

    static class c {
        static List<Object> list = Collections.synchronizedList(new LinkedList<>());

        static int size() {
            return list.size();
        }

        static void add(Object ele) {
            list.add(ele);
        }

        static Object get(int index) {
            return list.get(index);
        }
    }


    public static void main(String[] args) {
        final Object lock = new Object();

        new Thread(() -> {
            System.out.println("t2 启动");
            synchronized (lock) {
                if (c.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("t2 结束");
                //通知t1继续执行
                lock.notify();
            }

        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 启动");
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    c.add(new Object());
                    System.out.println("add " + i);

                    if (c.size() == 5) {
                        lock.notify();

                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "t1").start();
    }
}
